# -*- coding: utf-8 -*-
import requests

from src.config import app_config
from src.translation.base_tts import BaseTTS


class MicrosoftTTS(BaseTTS):
    def __init__(self):
        super().__init__()
        self.api_key = app_config.get('microsoft_tts.api_key')
        self.region = app_config.get('microsoft_tts.region')
        self.auth_token = None
        self.proxies = self._set_proxy()

    def _set_proxy(self):
        pro = app_config.get('proxy')
        if pro:
            return {"https": pro, "http": pro}
        return None

    def _get_auth_token(self):
        if not self.api_key:
            raise ValueError("Microsoft API key is not set in config.")
        if not self.region:
            raise ValueError("Microsoft region is not set in config.")

        url = f"https://{self.region}.api.cognitive.microsoft.com/sts/v1.0/issueToken"
        headers = {'Ocp-Apim-Subscription-Key': self.api_key}
        try:
            response = requests.post(url, headers=headers, timeout=10, proxies=self.proxies)
            response.raise_for_status()
            self.auth_token = str(response.text)
        except requests.exceptions.RequestException as e:
            raise Exception(f"Failed to get Microsoft TTS auth token: {e}")

    def get_voice_list(self):
        if not self.auth_token:
            self._get_auth_token()

        url = f"https://{self.region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
        headers = {'Authorization': f'Bearer {self.auth_token}'}
        try:
            response = requests.get(url, headers=headers, timeout=10, proxies=self.proxies)
            response.raise_for_status()
            voices = response.json()
            # Format for UI
            formatted_voices = []
            for voice in voices:
                formatted_voices.append({
                    "name": f"{voice['DisplayName']} ({voice['Locale']})",
                    "value": voice['ShortName']
                })
            return formatted_voices
        except requests.exceptions.RequestException as e:
            raise Exception(f"Failed to get Microsoft TTS voice list: {e}")

    def run(self, text, language, voice, rate, volume, pitch, output_file):
        if not self.auth_token:
            self._get_auth_token()

        url = f"https://{self.region}.tts.speech.microsoft.com/cognitiveservices/v1"
        headers = {
            'Authorization': f'Bearer {self.auth_token}',
            'Content-Type': 'application/ssml+xml',
            'X-Microsoft-OutputFormat': 'audio-24khz-48kbitrate-mono-mp3',
            'User-Agent': 'videotrans'
        }

        rate_str = f"{'+' if rate >= 0 else ''}{rate}%"
        volume_str = f"{'+' if volume >= 0 else ''}{volume}%"

        ssml = f"""
        <speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xml:lang='{language}'>
            <voice name='{voice}'>
                <prosody rate='{rate_str}' volume='{volume_str}'>
                    {text}
                </prosody>
            </voice>
        </speak>
        """

        try:
            response = requests.post(url, headers=headers, data=ssml.encode('utf-8'), timeout=300, proxies=self.proxies)
            response.raise_for_status()

            with open(output_file, 'wb') as f:
                f.write(response.content)
        except requests.exceptions.RequestException as e:
            raise Exception(f"Microsoft TTS request failed: {e}")
